package cn.tmpan.project.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * The type Jwt util.
 *
 * @Author tieMinPan
 * @Desc: Description
 * @Date 2019 -05-07 13:47
 */
public class JwtUtil {

    private final static String SECRET = PropertiesUtil.getProperty("", "SECRET");
    private final static String ISSUER = PropertiesUtil.getProperty("", "ISSUER");
    private final static String SUBJECT = PropertiesUtil.getProperty("", "SUBJECT");
    private final static String AUDIENCE = PropertiesUtil.getProperty("", "AUDIENCE");
    private final static Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);
    private final static String DATA_KEY = "DATA";

    /**
     * 创建token
     *
     * @param expireDate 过期时间
     * @param jsonStr    json字符串
     * @return string string
     */
    public static String createToken(Date expireDate, String jsonStr) {

        try {
            String token = JWT.create()
                    /**
                     *@desc /签名是有谁生成 例如 服务器
                     */
                    .withIssuer(ISSUER)
                    /**
                     *@desc 签名主题
                     */
                    .withSubject(SUBJECT)
                    /**
                     *@desc 定义在什么时间之前，该jwt都是不可用的.
                     */
                    .withNotBefore(new Date())
                    /**
                     *@desc 签名的观众 也可以理解谁接受签名
                     */
                    .withAudience(AUDIENCE)
                    /**
                     *@desc 生成签名的时间
                     */
                    .withIssuedAt(new Date())
                    /**
                     *@desc 签名过期的时间
                     */
                    .withExpiresAt(expireDate)
                    .withClaim(DATA_KEY, jsonStr)
                    /**
                     *@desc 签名 Signature
                     */
                    .sign(ALGORITHM);
            return token;
        } catch (JWTCreationException exception) {
            exception.printStackTrace();
        }
        return null;
    }


    /**
     * 解密token 返回参数
     *
     * @param token the token
     * @return string string
     */
    public static String verifyToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        try {
            JWTVerifier verifier = JWT.require(ALGORITHM)
                    .withIssuer(ISSUER)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims().get(DATA_KEY).asString();
        } catch (JWTVerificationException exception) {
            return null;
        }

    }

}
